package com.robot.util;

import com.robot.service.Task;
import com.robot.thread.TestPlanTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

/**
 * Created with IntelliJ IDEA.
 * User: li
 * Date: 2019/11/3
 * Time: 17:07
 * PROJECT：robot
 * PACKAGE: com.robot
 *
 * @author:55324936@qq.com To change this template use File | Settings | File Templates.
 */
@Component
public class TaskUtil {
    @Autowired
    ThreadPoolTaskScheduler taskScheduler;
    private static Map<String,ScheduledFuture<?>> scheduledFutureMap=new HashMap<>();
    /**
     * 新增定时任务
     * @param cron
     * @param testPlanTask
     * **/
    public void addTask(String cron,TestPlanTask testPlanTask){
        //时间表达式的初始化，构造方法的参数就是时间的表达式
        Trigger trigger =new CronTrigger(cron);
        ScheduledFuture<?>  scheduledFuture =taskScheduler.schedule(testPlanTask,trigger);
        scheduledFutureMap.put(testPlanTask.getTestPlanId().toString(),scheduledFuture);
    }
    /**
     * 取消定时任务
     * @param flag
     * **/
    public void cancel(String flag){
        ScheduledFuture<?> scheduledFuture =scheduledFutureMap.get(flag);
        if(null!=scheduledFuture) {
            scheduledFuture.cancel(true);
        }
    }
    /**
     * 修改定时任务
     * @param cron
     * @param testPlanTask
     * **/
    public void modify(String cron,TestPlanTask testPlanTask){
        this.cancel(testPlanTask.getTestPlanId().toString());
        this.addTask(cron,testPlanTask);
    }
}

